package dtd.PHS.VND_ExchangeRate;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import dtd.PHS.VND_ExchangeRate.SimpleGestureFilter.SimpleGestureListener;
import dtd.PHS.VND_ExchangeRate.VCB_ERate.MyCurrency;

public class CalculateRate extends Activity implements SimpleGestureListener{


	private EditText etEUR,etUSD,etVND;
	private EditText etFree01,etFree02;
	private ArrayList<EditText> editTexts;
	private Spinner spinner01,spinner02;
	private VCB_ERate vcb;
	private TextView tvDate;
	private MyMainMenu mainMenu;
	HashMap<EditText,VCB_ERate.MyCurrency> mapET2Curr;
	HashMap<Spinner, EditText> mapSpinner2ET;
	ArrayAdapter<MyCurrency> adapter;
	private dtd.PHS.VND_ExchangeRate.SimpleGestureFilter detector;
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyUtility.callOnEveryActivity(this);
		setContentView(R.layout.main);
		try {
			vcb = new VCB_ERate(this);
			mainMenu = new MyMainMenu(this);
			this.updateDateText();
			this.registerEditTexts();
			this.registerSpinnerTexts();
			this.detector = new SimpleGestureFilter(this, this);
		} catch (Exception e) {
			Toast.makeText(this, getString(R.string.no_internet_warning), Toast.LENGTH_LONG);
		}    
	}
	
	private void updateDateText() {
		this.tvDate = (TextView)findViewById(R.id.tvDate);
		tvDate.setText(tvDate.getText().toString() +" "+ vcb.getInputDate());		
	}

	private void registerSpinnerTexts() {
		etFree01 = (EditText)findViewById(R.id.etFree01);
		etFree02 = (EditText)findViewById(R.id.etFree02);		
		

		spinner01 = (Spinner)findViewById(R.id.spinner01);
		spinner02 = (Spinner)findViewById(R.id.spinner02);
		
		
		this.mapSpinner2ET = new HashMap<Spinner, EditText>();
		mapSpinner2ET.put(spinner01, etFree01);
		mapSpinner2ET.put(spinner02, etFree02);

		
		
		adapter = new ArrayAdapter<MyCurrency>(
				this, 
				android.R.layout.simple_spinner_item, 
				MyCurrency.values());
		
		spinner01.setAdapter(adapter);
		spinner02.setAdapter(adapter);
		
		registerEditTextAccSpinner( etFree01,spinner01 );
		registerEditTextAccSpinner( etFree02,spinner02 );

		
		MyOnItemSelectedListener listener = new MyOnItemSelectedListener();
		spinner01.setOnItemSelectedListener(listener);
		spinner02.setOnItemSelectedListener(listener);

		
	}

	private void registerEditTextAccSpinner(
			EditText et,
			Spinner sp) {
		MyCurrency c = (MyCurrency)sp.getSelectedItem();
		registerEditText(et, c);
	}

	private void registerEditTexts() {

		this.editTexts = new ArrayList<EditText>();
		this.mapET2Curr = new HashMap<EditText, MyCurrency>();
		
		etEUR = (EditText)findViewById(R.id.etEUR);		
		etUSD = (EditText)findViewById(R.id.etUSD);
		etVND = (EditText)findViewById(R.id.etVND);

		registerEditText(etEUR,MyCurrency.EUR);		
		registerEditText(etUSD,MyCurrency.USD);
		registerEditText(etVND,MyCurrency.VND);
		
	}

	private void registerEditText(EditText e,MyCurrency c) {
		this.mapET2Curr.put(e, c);		
		this.editTexts.add(e);
		e.addTextChangedListener(new MyTextWatcher(e));
	}



	class MyTextWatcher implements TextWatcher {

		private EditText toWatchEditText;
		private String oldText;
		private int oldPos;

		public MyTextWatcher(EditText e) {
			this.toWatchEditText = e;
		}

		public void afterTextChanged(Editable s) throws NumberFormatException{

			//Only activate the on changed EditText 
			if (this.toWatchEditText.findFocus() != null ) {
				String amount = MyUtility.getRidOfComma(s.toString());
				if ( MyUtility.isValidLong(amount) ) {
					this.updateEditTexts(toWatchEditText,amount);
				} 
			}
		}

		private void updateEditTexts(EditText onChangeET, String amount) {
			for (EditText e : mapET2Curr.keySet()) {
				if ( e.findFocus() == null ) {
					e.setText(MyUtility.formatCurrency(Long.toString(
							vcb.changeFromToBaseOnTransferRate(
									mapET2Curr.get(onChangeET), 
									mapET2Curr.get(e), 
									Long.parseLong(amount)
							))));
				} 
				else {
					String afterString = MyUtility.formatCurrency(amount);
					if ( ! afterString.equals( onChangeET.getText().toString() ) ) {			
						int newCursorPosition = MyUtility.newCursorPosition(this.oldPos,this.oldText,afterString);
						onChangeET.setText(afterString);
						Editable etext = onChangeET.getText(); 
						Selection.setSelection(etext, newCursorPosition);
					}
				}
			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			this.oldText = s.toString();
			this.oldPos = Selection.getSelectionStart(this.toWatchEditText.getText());
			

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			

		}

	}
	private void forceUpdateEditText(EditText et) {
		if (etVND.getText().toString().equals("")) return;
		String amountVNDString = MyUtility.getRidOfComma(etVND.getText().toString());
		long amountVND = Long.parseLong(amountVNDString);
		long amountExchange =
			vcb.changeFromToBaseOnTransferRate(
				mapET2Curr.get(etVND), 
				mapET2Curr.get(et), 
				amountVND);
 
		et.setText(MyUtility.formatCurrency(Long.toString(amountExchange)));
	
	}
	
	public void onClickIBListRateHandler(View view) {
		Intent intent = new Intent(this,ListRates.class);
		this.startActivity(intent);
	}
	
	
	public void onClickSMSHandler(View view) {
		Intent intent = new Intent(this,SendSMS.class);
		this.startActivity(intent);	
	}
	
	//TODO: copy & test change on hdpi + language
	public void onClearClickHandler(View view) {
		for(EditText et : this.editTexts) {
			et.setText("");
		}
	}
	
	public void onSendSMSClickHandler(View view) {
		Intent intent = new Intent(this,PreviewSMS.class);
		this.saveDataToPass();
		
		startActivity(intent);
	}
	
	private void saveDataToPass() {
		int numCurrencies = this.editTexts.size();
		MyUtility.passData_Calculate2PreviewSMS_amount = new String[numCurrencies];
		MyUtility.passData_Calculate2PreviewSMS_currencies = new String[numCurrencies];
		MyUtility.passData_Calculate2PreviewSMS_inputDate =this.vcb.getInputDate();
		int i = 0;
		for(EditText et : this.editTexts) {
			String amount = et.getText().toString();
			String currency = this.mapET2Curr.get(et).toString();
			MyUtility.passData_Calculate2PreviewSMS_amount[i] = amount;
			MyUtility.passData_Calculate2PreviewSMS_currencies[i] = currency;
			i++;
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		mainMenu.createOptionsMenu(menu);
	    return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		return mainMenu.onItemSelected(item);	
	}


	public class MyOnItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View aSpinner, int pos,
				long id) {			
			MyCurrency c = (MyCurrency) parent.getSelectedItem();
			EditText et = mapSpinner2ET.get(((Spinner)parent));
			mapET2Curr.put(et, c);
			forceUpdateEditText(et);
		}

		public void onNothingSelected(AdapterView<?> arg0) {
			
		}
		
	}
	
	@Override 
	public boolean dispatchTouchEvent(MotionEvent me){ 
		this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me); 
	}
	
	@Override
	public void onDoubleTap() {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onSwipe(int direction) {
		switch (direction) {
		case SimpleGestureFilter.SWIPE_LEFT:
			this.startActivity(new Intent(this,SendSMS.class));
			break;
		case SimpleGestureFilter.SWIPE_RIGHT:
			this.startActivity(new Intent(this,ListRates.class));
			break;
		default:
			break;
		}
		
	}


}